package cn.com.dhcc.turbo.web.controller.exch;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.ftpserver.usermanager.SaltedPasswordEncryptor;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.util.CollectionUtil;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.app.pub.core.listener.FtpletListener;
import cn.com.dhcc.turbo.entity.registry.AdapterBase;
import cn.com.dhcc.turbo.entity.registry.FtpUser;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.registry.NodePipeline;
import cn.com.dhcc.turbo.entity.registry.NodePipeline.PIPE_TYPE;
import cn.com.dhcc.turbo.service.exch.exhmgr.FtpUserService;
import cn.com.dhcc.turbo.service.monitor.FtpOnlineUser;
import cn.com.dhcc.turbo.service.registry.AdapterBaseService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;
import cn.com.dhcc.turbo.service.registry.NodePipelineService;
import cn.com.dhcc.turbo.service.registry.vo.PipeLineFtp;
import cn.com.dhcc.turbo.service.transport.FtpService;

/**
 * Created by zss on 2014/6/11.
 */
@Controller
@RequestMapping("/exch")
@TurboMenu(belongToMenu= TurboMenu.LEAF_MENU.FTP_MGR)
public class FtpMgrController extends BaseController {
    @SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(Log.LOGTYPE.SAI);
    @Autowired
    private FtpUserService ftpUserService;
  
    @Autowired
    private AdapterBaseService adapterBaseService;
    @Autowired
    NodeInfoService nodeInfoService;
    @Autowired
    NodePipelineService nodePipelineService;
    @Autowired
    FtpService ftpService;
    @RequestMapping(value = "/ftp_mgr")
    public String list(Model model, Pager pager, String searchName) {
        try {
           
            WhereCondition condition = new WhereCondition();
            condition.where().eq("enableflag", "1").and().notEq("userid", AppConst.EMBFTP.EMBFTP_ADMIN_USERID);

            if (!"".equals(searchName) && searchName != null) {
                condition.and().eq("userid", searchName);
            }
            NodeInfo localNodeInfo = nodeInfoService.getLocalNode();
            NodePipeline nodePipelineFtp =  nodePipelineService.getEmbedPipeLine(localNodeInfo.getId(),PIPE_TYPE.FTP_EMBED);
            String status = nodePipelineFtp.getStatus();
            PipeLineFtp pipeLineFtpInDb = nodePipelineService.getFtpConfByNodeId(localNodeInfo.getId()); 
            pipeLineFtpInDb.setStatus(status);
            pipeLineFtpInDb.setLastStartTime(FtpletListener.startTime);
            PagerData<FtpUser> pagerData = ftpUserService.getPagerList(pager,
                    condition);
            injectOnlineStatus(pagerData.getDatas());
            
            List<AdapterBase> adapterList=adapterBaseService.list(new WhereCondition());
            model.addAttribute(DATA_KEY, pagerData.getDatas());
            model.addAttribute("locaFtpInfo", pipeLineFtpInDb);
            model.addAttribute("adapterList", adapterList);
//            System.out.println(adapterList);
            setTotoal(model, pagerData.getTotal());
        } catch (Exception e) {
            logger.error("获取业务域信息失败", e);
            return toAlertPage(model, e.getMessage());
        }
        return "exch/ftp_mgr";
    }
    private void injectOnlineStatus(List<FtpUser> datas) {
    	Map<String, FtpOnlineUser> loginUsers = FtpletListener.getLoginUsers();
    	if(CollectionUtil.hasElement(datas)){
    		for (Iterator<FtpUser> iterator = datas.iterator(); iterator.hasNext();) {
				FtpUser ftpUser = (FtpUser) iterator.next();
				if(loginUsers.containsKey(ftpUser.getUserid())){
					ftpUser.setOnlineShowStr(loginUsers.get(ftpUser.getUserid()).getShowStr());
				}else{
					ftpUser.setOnlineShowStr("未在线");
				}
			}
    	}
		
	}
	@RequestMapping(value = "/open_ftp")
    @ResponseBody
    public Map<String, Object> openFtp() {
        try {
        	ftpService.startFtpServer();
        	return jsonSuccessResult("FTP启动成功!");
        } catch (NiceException e) {
            return jsonFailResult(e.getMessage());
        }
    }
    @RequestMapping(value = "/reset_ftp_password/{id}")
    @ResponseBody
    public Map<String, Object> resetFtpPassword(@PathVariable String id) {
        String message = "重置密码失败";
        try {
            FtpUser ftpUser = ftpUserService.get(id);
            SaltedPasswordEncryptor saltedPasswordEncryptor = new SaltedPasswordEncryptor();
            String password = saltedPasswordEncryptor.encrypt(id);
            ftpUser.setUserpassword(password);
            int i = ftpUserService.update(ftpUser);
            if (i == 1) {
                message = "重置密码成功，新密码和FTP用户名相同为："+id;
            }
        } catch (Exception e) {
            return jsonFailResult(message);
        }
        return jsonSuccessResult(message);
    }

    @RequestMapping(value = "/ftp_password_update/{id}")
    public String ftpPasswordUpdate(Model model, @PathVariable String id) {
        model.addAttribute(DATA_KEY, id);
        return "exch/ftp_password_update";
    }

    @RequestMapping(value = "/update_ftp_password")
    @ResponseBody
    public Map<String, Object> updateFtpPassword(String userid, String oldpassword, String newpassword) {
        String message = "修改密码失败";
        try {
            FtpUser ftpUser = ftpUserService.get(userid);
            SaltedPasswordEncryptor saltedPasswordEncryptor = new SaltedPasswordEncryptor();
            String passwordstore = ftpUser.getUserpassword();
            boolean b = saltedPasswordEncryptor.matches(oldpassword, passwordstore);
            if (!b) {
                message = "原密码不正确";
                return jsonFailResult(message);
            }
            String newpasswordstore = saltedPasswordEncryptor.encrypt(newpassword);
            ftpUser.setUserpassword(newpasswordstore);
            int i = ftpUserService.update(ftpUser);
            if (i == 1) {
                message = "修改密码成功";
            }
        } catch (Exception e) {
            return jsonFailResult(message);
        }
        return jsonSuccessResult(message);
    }
}
